"""
购物车相关视图
"""
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from pecco_site.models import Cart, CartItem, ProductVariant
from ..serializers.cart import (
    CartSerializer, CartItemSerializer, AddToCartSerializer,
    UpdateCartItemSerializer
)


class CartViewSet(viewsets.ViewSet):
    """购物车视图集"""
    permission_classes = [AllowAny]  # 允许未登录用户访问
    
    def get_cart(self, request):
        """获取或创建购物车"""
        if request.user.is_authenticated:
            # 登录用户使用用户关联的购物车
            cart, created = Cart.objects.get_or_create(user=request.user)
            
            # 如果有session购物车，合并到用户购物车
            session_key = request.session.session_key
            if session_key:
                session_cart = Cart.objects.filter(session_key=session_key, user__isnull=True).first()
                if session_cart:
                    # 合并购物车
                    for item in session_cart.items.all():
                        cart_item, created = CartItem.objects.get_or_create(
                            cart=cart,
                            variant=item.variant,
                            defaults={'quantity': item.quantity}
                        )
                        if not created:
                            cart_item.quantity += item.quantity
                            cart_item.save()
                    # 删除session购物车
                    session_cart.delete()
        else:
            # 未登录用户使用session购物车
            if not request.session.session_key:
                request.session.create()
            session_key = request.session.session_key
            cart, created = Cart.objects.get_or_create(session_key=session_key, user__isnull=True)
        
        return cart
    
    def list(self, request):
        """查看购物车"""
        cart = self.get_cart(request)
        serializer = CartSerializer(cart, context={'request': request})
        return Response(serializer.data)
    
    @action(detail=False, methods=['post'])
    def add(self, request):
        """添加商品到购物车"""
        serializer = AddToCartSerializer(data=request.data)
        if serializer.is_valid():
            variant_id = serializer.validated_data['variant_id']
            quantity = serializer.validated_data['quantity']
            
            try:
                variant = ProductVariant.objects.get(id=variant_id)
                
                # 获取或创建购物车
                cart = self.get_cart(request)
                
                # 计算本次加购后的总数量（已有数量 + 新增数量）
                cart_item = CartItem.objects.filter(cart=cart, variant=variant).first()
                existing_quantity = cart_item.quantity if cart_item else 0
                new_total_quantity = existing_quantity + quantity
                
                # 添加调试日志
                print(f"[DEBUG] 添加到购物车: variant_id={variant_id}, stock={variant.stock}, existing={existing_quantity}, adding={quantity}, new_total={new_total_quantity}")
                
                # 严格校验库存（不允许超过可用库存）
                if new_total_quantity > variant.stock:
                    print(f"[DEBUG] 库存不足，拒绝添加")
                    return Response({
                        'error': f'Insufficient stock. Only {variant.stock} items available.'
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                # 更新或创建购物车条目
                if cart_item:
                    cart_item.quantity = new_total_quantity
                    cart_item.save()
                else:
                    CartItem.objects.create(cart=cart, variant=variant, quantity=quantity)
                
                print(f"[DEBUG] 添加成功")
                cart_serializer = CartSerializer(cart, context={'request': request})
                return Response({
                    'message': 'Item added to cart successfully',
                    'cart': cart_serializer.data
                }, status=status.HTTP_200_OK)
                
            except ProductVariant.DoesNotExist:
                return Response({
                    'error': 'Product variant not found'
                }, status=status.HTTP_404_NOT_FOUND)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['put'], url_path='update/(?P<item_id>[^/.]+)')
    def update_item(self, request, item_id=None):
        """更新购物车项目数量"""
        serializer = UpdateCartItemSerializer(data=request.data)
        if serializer.is_valid():
            quantity = serializer.validated_data['quantity']
            
            cart = self.get_cart(request)
            
            try:
                cart_item = CartItem.objects.get(id=item_id, cart=cart)
                
                # 检查库存：只在数量大于当前数量时检查（即增加数量时）
                # 如果是减少数量，则允许（即使当前数量已超过库存）
                if quantity > cart_item.quantity and quantity > cart_item.variant.stock:
                    return Response({
                        'error': f'Insufficient stock. Only {cart_item.variant.stock} items available.'
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                cart_item.quantity = quantity
                cart_item.save()
                
                cart_serializer = CartSerializer(cart, context={'request': request})
                return Response({
                    'message': 'Cart item updated successfully',
                    'cart': cart_serializer.data
                }, status=status.HTTP_200_OK)
                
            except CartItem.DoesNotExist:
                return Response({
                    'error': 'Cart item not found'
                }, status=status.HTTP_404_NOT_FOUND)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['delete'], url_path='remove/(?P<item_id>[^/.]+)')
    def remove_item(self, request, item_id=None):
        """从购物车移除商品"""
        cart = self.get_cart(request)
        
        try:
            cart_item = CartItem.objects.get(id=item_id, cart=cart)
            cart_item.delete()
            
            cart_serializer = CartSerializer(cart, context={'request': request})
            return Response({
                'message': 'Item removed from cart successfully',
                'cart': cart_serializer.data
            }, status=status.HTTP_200_OK)
            
        except CartItem.DoesNotExist:
            return Response({
                'error': 'Cart item not found'
            }, status=status.HTTP_404_NOT_FOUND)
    
    def partial_update(self, request, pk=None):
        """更新购物车项目数量 (PATCH /cart/{id}/)"""
        cart = self.get_cart(request)
        
        try:
            cart_item = CartItem.objects.get(id=pk, cart=cart)
        except CartItem.DoesNotExist:
            return Response({
                'error': 'Cart item not found'
            }, status=status.HTTP_404_NOT_FOUND)
        
        serializer = UpdateCartItemSerializer(data=request.data)
        if serializer.is_valid():
            quantity = serializer.validated_data['quantity']
            
            # 如果数量为0，删除商品
            if quantity == 0:
                cart_item.delete()
                cart_serializer = CartSerializer(cart, context={'request': request})
                return Response({
                    'message': 'Cart item removed successfully',
                    'cart': cart_serializer.data
                }, status=status.HTTP_200_OK)
            
            # 检查库存：只在数量大于当前数量时检查（即增加数量时）
            # 如果是减少数量，则允许（即使当前数量已超过库存）
            if quantity > cart_item.quantity and quantity > cart_item.variant.stock:
                return Response({
                    'error': f'Insufficient stock. Only {cart_item.variant.stock} items available.'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            cart_item.quantity = quantity
            cart_item.save()
            
            cart_serializer = CartSerializer(cart, context={'request': request})
            return Response({
                'message': 'Cart item updated successfully',
                'cart': cart_serializer.data
            }, status=status.HTTP_200_OK)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, pk=None):
        """删除购物车项目 (DELETE /cart/{id}/)"""
        cart = self.get_cart(request)
        
        try:
            cart_item = CartItem.objects.get(id=pk, cart=cart)
            cart_item.delete()
            
            cart_serializer = CartSerializer(cart, context={'request': request})
            return Response({
                'message': 'Item removed from cart successfully',
                'cart': cart_serializer.data
            }, status=status.HTTP_200_OK)
        except CartItem.DoesNotExist:
            return Response({
                'error': 'Cart item not found'
            }, status=status.HTTP_404_NOT_FOUND)
    
    @action(detail=False, methods=['post'])
    def clear(self, request):
        """清空购物车"""
        cart = self.get_cart(request)
        cart.items.all().delete()
        
        cart_serializer = CartSerializer(cart, context={'request': request})
        return Response({
            'message': 'Cart cleared successfully',
            'cart': cart_serializer.data
        }, status=status.HTTP_200_OK)


